package game.scene.sceneobject;

import java.util.ArrayList;

import common.Coordinate;
import common.Log;
import common.Rectangle;

import engine.video.blit.BlitMode_E;
import engine.video.blit.Blitter;

public class Container_SO extends SceneObject_A {
	private Coordinate _Location;
	
	public Container_SO() {
		_Objects = new ArrayList<SceneObject_A>();
		_Location = new Coordinate();
	}
	
	private final ArrayList<SceneObject_A> _Objects;
	
	public SceneObject_A get(int index) {
		return _Objects.get(index);
	}
	public void add(SceneObject_A sceneObject) {
		_Objects.add(sceneObject);
		calculateBounds().copyTo(this.VisRect);
	}
	public void remove(SceneObject_A sceneObject) {
		_Objects.remove(sceneObject);
		calculateBounds().copyTo(this.VisRect);
	}
	public void removeAll() {
		_Objects.clear();
		calculateBounds().copyTo(this.VisRect);
	}

	private Rectangle calculateBounds() {
		int x1 = 0;
		int y1 = 0;
		int x2 = 0;
		int y2 = 0;
		int sx1, sy1, sx2, sy2;
		for(SceneObject_A so : _Objects) {
			sx1 = so.VisRect.X;
			sy1 = so.VisRect.Y;
			sx2 = so.VisRect.X + so.VisRect.Width;
			sy2 = so.VisRect.Y + so.VisRect.Height;
			
			if(sx1 < x1) {
				x1 = sx1;
			}
			if(sx2 > x2) {
				x2 = sx2;
			}
			if(sy1 < y1) {
				y1 = sy1;
			}
			if(sy2 > y2) {
				y2 = sy2;
			}
		}
		return new Rectangle(x1, y1, x2 - x1, y2 - y1);
	}
	@Override
	public boolean isOverlapping(Rectangle queryRect) {
		return this.VisRect.overlaps(queryRect);
	}

	@Override
	public void render(Coordinate camera, Blitter buffer) {
		Coordinate localCamera = new Coordinate(camera.X - _Location.X, camera.Y - _Location.Y);
		for(SceneObject_A so : _Objects) {
			so.render(localCamera, buffer);
		}
	}

	@Override
	public void setLocation(Coordinate location) {
		this.VisRect.X += (location.X - _Location.X);
		this.VisRect.Y += (location.Y - _Location.Y);
		_Location.X = location.X;
		_Location.Y = location.Y;
	}

	@Override
	public void setBoundry(Rectangle boundry) {
		return;
	}
}
